package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.MultiLinesView;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.Date;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/4/8 12:08
 */
public class QualityInspetionDetailFragment extends BaseFragment implements View.OnClickListener {
  public static final String EXTRA_ID =
      QualityInspetionDetailFragment.class.getSimpleName() + "EXTRA_ID";
  private static final int REQUEST_DATE = 1;
  private static final int REQUEST_FILE_SELECT = 2;
  private static final int REQUEST_UPLOAD = 3;
  private static final int REQUEST_LEVEL = 4;
  @BindView(R.id.sl_customerEvaluation) MultiLinesView mSlCustomerEvaluation;
  @BindView(R.id.sl_level) SingleLineView mSlLevel;
  @BindView(R.id.sl_checkDate) SingleLineView mSlCheckDate;
  @BindView(R.id.sl_checkStaffNameQualityInspetion) SingleLineView
      mSlCheckStaffNameQualityInspetion;
  @BindView(R.id.sl_docBlobQualityInspetion) SingleLineView mSlDocBlobQualityInspetion;
  //@BindView(R.id.sl_cropCheck)
  //MultiLinesView mSlCropCheck;
  private View mView;
  private String mId;
  private String mLevel;
  private String mDocPath;

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    initData();
    initView(inflater, container, savedInstanceState);
    return mView;
  }

  public static Fragment newInstance(String id) {
    QualityInspetionDetailFragment fragment = new QualityInspetionDetailFragment();
    Bundle args = new Bundle();
    args.putString(EXTRA_ID, id);
    fragment.setArguments(args);
    return fragment;
  }

  @SuppressWarnings("all")
  private void initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_quality_inspetion_update, container, false);
    ButterKnife.bind(this, mView);
    setTitleCustom(MyStringUtil.connect(R.string.add, R.string.qualityInspetion));
    mSlCheckDate.setOnClickContentListener(this);
    mSlDocBlobQualityInspetion.setOnClickContentListener(this);
    mSlLevel.setOnClickContentListener(this);
  }

  public void initData() {
    if (getArguments() != null) {
      mId = getArguments().getString(EXTRA_ID);
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_confirm, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_confirm:
        volleyPostSave();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPostSave() {
    if (mSlCheckDate.isEmptyContent()
        || mSlCheckStaffNameQualityInspetion.isEmptyContent()
        || mSlCustomerEvaluation.isEmptyContent()
        || mSlLevel.isEmptyContent()) {
      ToastUtil.show(R.string.completeWrite);
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_QUALITYINSPETION);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("mainId", mId);
    params.put("id", UUID.randomUUID().toString());
    params.put("customerEvaluation", mSlCustomerEvaluation.getTextContent());
    params.put("level", mLevel);
    params.put("levelName", mSlLevel.getTextContent());
    params.put("checkDate", mSlCheckDate.getTextContent());
    params.put("docBlob", mSlDocBlobQualityInspetion.getTextContent());
    params.put("docPath", mDocPath);
    params.put("checkStaffName", mSlCheckStaffNameQualityInspetion.getTextContent());
    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        Base original = new Gson().fromJson(json, Base.class);
        ToastUtil.show(original.getMessage());
        if (original.getResult() == Base.SUCCESS) {
          mActivity.setResult(Activity.RESULT_OK);
          mActivity.finish();
        }
      }
    });
  }

  @Override public void onClick(View v) {
    if (!(v.getTag() instanceof Integer)) return;
    int id = (int) v.getTag();
    if (id == R.id.sl_checkDate) {
      selectDate();
    }
    if (id == R.id.sl_docBlobQualityInspetion) {
      selectDoc();
    }
    if (id == R.id.sl_level) {
      selectLevel();
    }
  }

  private void selectLevel() {
    DialogFragment dialog = new LevelNetworkDialogFragment();
    dialog.setTargetFragment(this, REQUEST_LEVEL);
    dialog.show(getActivity().getSupportFragmentManager(), "");
  }

  /**
   * 选择附件上传
   */
  private void selectDoc() {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        REQUEST_FILE_SELECT);
  }

  protected void selectDate() {
    DialogFragment dialog = BaseTimeDialogFragment.newInstance(new Date());
    dialog.setTargetFragment(this, REQUEST_DATE);
    dialog.show(getActivity().getSupportFragmentManager(), "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_DATE && data != null) {
      Date date = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      mSlCheckDate.setTextContent(DateFormat.format(MyDateUtil.TYPE_ALL, date).toString());
    }
    if (requestCode == REQUEST_FILE_SELECT && data != null) {
      String path = FileUtil.getPath(getActivity(), data.getData());
      if (!TextUtils.isEmpty(path)) {

        FileUploadDialgFragment dialog =
            FileUploadDialgFragment.newInstance(path, mId, "imsifwj.quality_inspetion");
        dialog.setTargetFragment(this, REQUEST_UPLOAD);
        dialog.show(mActivity.getSupportFragmentManager(), "");
      }
    }
    if (requestCode == REQUEST_UPLOAD) {
      mDocPath = data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH);
      mSlDocBlobQualityInspetion.setTextContent(FileUtil.getFileNameByFilePath(mDocPath));
    }
    if (requestCode == REQUEST_LEVEL && data != null) {
      CustomerDialog value =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      mSlLevel.setTextContent(value.getName());
      mLevel = value.getId();
    }
  }
}
